<template>
  <el-dialog :title="'人员导入'" :close-on-click-modal="false" :visible.sync="visible"
    @close="clearDataList()" width="1200px" top="8vh">

    <basic-container>
      <div class="flex justifyContentSpaceBetween mb5">
        <div v-show="showExist" class="tabletext">数据状态管理</div>
        <div class="tablelink">
        <el-upload
          class="upload-demo"
          action="/admin/sys-file/upload"
          accept=".xls,.xlsx"
          :headers="headers"
          :before-upload="beforeFileUpload"
          :on-change="handleChange"
          :on-success="handleUploadSuccess"
          :show-file-list="false"
          :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <!--:show-file-list="false" -->
          <!--<div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>-->
        </el-upload>
      </div>
      </div>
      <div v-show="showExist">
        <!-- <div class="flex mb5" style="align-items: center;">
          <span> 新增：</span>
          <span>
            <el-radio-group v-model="staOptionsAdd">
              <el-radio-button label="新增" border>新增</el-radio-button>
              <el-radio-button label="新增不操作" border>不操作</el-radio-button>
            </el-radio-group>
          </span>
            <span class="ml10">修改：</span>
            <span>
            <el-radio-group v-model="staOptionsEdit">
              <el-radio-button label="修改" border>修改</el-radio-button>
              <el-radio-button label="修改不操作" border>不操作</el-radio-button>
            </el-radio-group>
            </span>
            <span v-show="false" class="ml10">历史留存：</span>
            <span v-show="false">
              <el-radio-group v-model="staOptionsExist">
                <el-radio-button label="删除" border>删除</el-radio-button>
                <el-radio-button label="删除不操作" border>不操作</el-radio-button>
              </el-radio-group>
            </span>
        </div> -->
        <el-row>
          <el-table :data="tableData"  v-loading="bLoading"  element-loading-text="拼命加载中"
                    element-loading-spinner="el-icon-loading" element-loading-background="rgba(250, 245, 245, 0.8)"
                    tooltip-effect="dark" height="500px" style="width: 100%"  border stripe>
            <el-table-column type="index" align="center" width="55" fixed></el-table-column>
            <el-table-column label="数据状态"  align="center" width="90" fixed>
              <template slot-scope="scope">
                  <span v-if="scope.row.rySjzt === '错误'"><span style="color: red">{{scope.row.rySjzt}}</span></span>
                  <span v-else-if="scope.row.rySjzt === '新增'">{{scope.row.rySjzt}}</span>
                  <span v-else-if="scope.row.rySjzt === '修改'">{{scope.row.rySjzt}}</span>
                  <span v-else-if="scope.row.rySjzt === '历史留存'"><span style="color:cornflowerblue">{{scope.row.rySjzt}}</span></span>
                  <span v-else>{{scope.row.rySjzt}}</span>
              </template>

            </el-table-column>
            <el-table-column label="人员编号" width="120" fixed>
              <template slot-scope="scope">{{ scope.row.ryCode }}</template>
            </el-table-column>
            <el-table-column prop="ryXm" label="姓名" width="100"  fixed></el-table-column>
            <el-table-column label="数据检测" min-width="100" >
              <template slot-scope="scope"><span style="color: red">{{ scope.row.rySjjc }}</span></template>
            </el-table-column>
<!--            <el-table-column prop="ryZhiwei" label="职位" min-width="120"></el-table-column>-->
            <el-table-column prop="ryZhiwu" label="职务" min-width="120"></el-table-column>
            <el-table-column prop="ryZwjb" label="岗位层级" min-width="120"></el-table-column>
<!--            <el-table-column prop="ryYgzt" label="附加员工状态" min-width="120"></el-table-column>
            <el-table-column prop="ryEjdw" label="所属二级单位" min-width="200"></el-table-column>-->
            <el-table-column prop="rySjdw" label="所属三级单位" min-width="200"></el-table-column>
<!--            <el-table-column prop="ryGzfw" label="工资范围" min-width="180"></el-table-column>-->
          </el-table>
        </el-row>
      </div>
    </basic-container>

    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="btnConfirm" >确定导入</el-button>
      <el-button @click="clearDataList">关闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import store from '@/store'
import request from '@/router/axios'
import {saveAllRyxxbList} from '@/api/admin/sysryxxb';
import {fetchTree,getTreeList} from '@/api/admin/dept'
import {remote as remoteDict } from '@/api/admin/dict'
import {getRyxxListPermissionNone} from '@/api/jiangjin/jiangjinryxxb';


export default {
 data(){
   return{
     bLoading:false,
     visible: false,
     //页面展示数据
     tableData: [],
     //导入Excel数据
     tableImpExcel:[],
     //数据库数据
     tableDBData:[],
     //rySjzt 数据状态 错误，新增，修改、删除
     tableErr:[],
     tableAdd:[],
     tableEdit:[],
     tableDel:[],
     //====
     staOptionsAdd:'新增',//'新增不操作',
     staOptionsEdit:'修改',//'修改不操作',
     staOptionsExist:'删除不操作',
     //====
     fileList:[],
     showExist:false,
     headers: {
       Authorization: 'Bearer ' + store.getters.access_token
     },
     listQuery: {
       name: undefined
     },
     listTree:[],
     //新增职级下拉
     userZjOptions:[],
   }
 },
 methods:{
   handleUploadSuccess(response, file, fileList) {
     ////console.log('3232323')  show-overflow-tooltip
     this.showExist = true;
      this.$message.closeAll()
     if (response.code !== 0) {
       this.$message.error('上传出错：' + response.msg)
       return;
     }

     ////console.log(response.data.bucketName);//jxkh
     ////console.log(response.data.fileName);  //2021/07/27/09de9b8ed2e14996ba6b3a155d0a6884.xlsx
      this.bLoading = true;

       request({
         url: '/jiangjin/jiangjinryxxb/fileRyxx/' + response.data.bucketName + '/' + response.data.fileName,
         method: 'get',
       }).then((res) => {
         this.tableImpExcel = [];
         this.tableImpExcel = res.data.data;
         ////console.log(this.tableImpExcel);
         this.setTableData();
         this.bLoading = false;
         // getRyxxListPermissionNone().then( nres => {
         //   this.tableDBData = [];
         //   this.tableDBData = nres.data.data;
         //
         //   this.setTableData();
         //   this.bLoading = false;
         // }).catch(err =>{
         //   this.bLoading = false;
         // })
         // this.setTableData();
         // this.bLoading = false;
       }).catch(error =>{
         this.bLoading = false;
       })


   },
   handleChange(file, fileList){
     this.fileList = [];
     this.fileList.push(file);
   },
   beforeFileUpload(file){
    ////console.log(file);
    const cType = file.type;
    let isXls = false;

    // const isXls = file.type === 'xls/xlsx';
    if(cType === "application/vnd.ms-excel" ||
      cType === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){
      isXls = true;
    }
    this.$message.closeAll()
    if (!isXls) {
       this.$message.error('导入文件只能是 Excel 格式!');
     }
     return isXls;
   },
   //初始化
   initNone(){

   },
   init () {
     this.visible = true;
     getTreeList(this.listQuery).then(response => {
       this.listTree = [];
       this.listTree = response.data.data
       ////console.log(this.listTree);
     })

     remoteDict("user_zj").then(response => {
       this.userZjOptions = response.data.data
     })

   },
   //取得提示数据
   getInformation(str){
    let lResult = "";

    if(str.length > 2){
      lResult = "不操作";
    }else {
      lResult = str;
    }
    return lResult;
   },
   //取得所有处理数据
   getHandleData(){
      let lTemp = [];
      if(this.staOptionsAdd === "新增" && this.tableAdd.length > 0 ) {
        lTemp = this.tableAdd;
      }
     if(this.staOptionsEdit === "修改" && this.tableEdit.length > 0) {
       lTemp =lTemp.concat(this.tableEdit);
     }
     if(this.staOptionsExist === "删除" && this.tableDel.length > 0){
       lTemp = lTemp.concat(this.tableDel);
     }
      return lTemp;
   },
   //确定
   btnConfirm(){
     let lMessage = "";
     const cData = this.getHandleData();

     if(cData.length === 0){
       this.$notify.closeAll();
       this.$notify.error('无可操作项！');
       return;
     }

     lMessage = "确定数据状态 新增("+ this.getInformation(this.staOptionsAdd) +"),";
     lMessage +="修改("+this.getInformation(this.staOptionsEdit)+")";
     // lMessage +=",历史留存("+this.getInformation(this.staOptionsExist)+")";

     this.$confirm(lMessage, '提示', {
       confirmButtonText: '确定',
       cancelButtonText: '取消',
       type: 'warning'
     }).then(() => {
       const loading = this.$loading({
         lock: true,
         text: 'Loading',
         spinner: 'el-icon-loading',
         background: 'rgba(0, 0, 0, 0.7)'
       });

       saveAllRyxxbList(cData).then(res =>{
           this.$notify.closeAll();
           this.$notify.success('数据操作成功');
           loading.close();
           this.clearDataList();
           this.$emit("refreshDataList");
       }).catch((err) => {
         loading.close();
         this.$notify.closeAll();
         this.$notify.success('数据操作失败');
       });


     }).catch((err) => {

     });


   },
   //Excel里是否有记录
   getExistFromExcel(sourceExcel,contrastValue){
     let lExist = false;
     sourceExcel.find(value =>{
       if(contrastValue.trim() === value.ryCode.trim()){
         lExist = true;
       }
     })
     return lExist;
   },
   //取得DB里有，excel里没有的数据
   getNoneExistFromExcel(sourceExcel){
     for(let i=0;i<this.tableDBData.length;i++){
       bExist = false;
       bExist = this.getExistFromExcel(sourceExcel,this.tableDBData[i].ryCode)
       if (bExist) continue;

       this.$set(this.tableDBData[i],"rySjzt","历史留存");//数据状态
       this.$set(this.tableDBData[i],"rySjjc","");      //数据检查
       this.$set(this.tableDBData[i],"dataState",0);
       this.tableDel.push(this.tableDBData[i]);
     }
   },
   //岗位层级验证
   getZwjbRepeat(value){
     let lResult = "";
     for(let item of this.userZjOptions){
       if(item.label.trim() === value.trim()){
         lResult = item.value;
         break;
       }
     }
     return lResult;
   },
   //Excel数据校验
   getRightData(){
      let Str = [];
      let lTemp = "";

     for(let i=0;i<this.tableImpExcel.length;i++){

       if(this.tableImpExcel[i].ryCode.trim() === ""){
         this.$set(this.tableImpExcel[i],"rySjzt","错误");
         this.$set(this.tableImpExcel[i],"rySjjc","人员编号为空");
         this.tableErr.push(this.tableImpExcel[i]);
         continue;
       }

       if(this.tableImpExcel[i].ryXm.trim() === ""){
         this.$set(this.tableImpExcel[i],"rySjzt","错误");
         this.$set(this.tableImpExcel[i],"rySjjc","姓名为空");
         this.tableErr.push(this.tableImpExcel[i]);
         continue;
       }

       //岗位层级特殊处理 20210906
       if(this.tableImpExcel[i].ryZwjb.trim() === ""){
         this.$set(this.tableImpExcel[i],"rySjzt","错误");
         this.$set(this.tableImpExcel[i],"rySjjc","岗位层级为空");
         this.tableErr.push(this.tableImpExcel[i]);
         continue;
       }else {
         lTemp = "";
         lTemp = this.getZwjbRepeat(this.tableImpExcel[i].ryZwjb);
         if(lTemp === ""){
           this.$set(this.tableImpExcel[i],"rySjzt","错误");
           this.$set(this.tableImpExcel[i],"rySjjc","无此岗位层级");
           this.tableErr.push(this.tableImpExcel[i]);
           continue;
         }else{
           this.$set(this.tableImpExcel[i],"ryZwjbbh",lTemp);
         }
       }

       // if(this.tableImpExcel[i].ryEjdw.trim() === ""){
       //   this.$set(this.tableImpExcel[i],"rySjzt","错误");
       //   this.$set(this.tableImpExcel[i],"rySjjc","所属二级单位为空");
       //   this.tableErr.push(this.tableImpExcel[i]);
       //   continue;
       // }

       if(this.tableImpExcel[i].rySjdw.trim() === ""){
         this.$set(this.tableImpExcel[i],"rySjzt","错误");
         this.$set(this.tableImpExcel[i],"rySjjc","所属三级单位为空");
         this.tableErr.push(this.tableImpExcel[i]);
         continue;
       }

       // if(this.tableImpExcel[i].ryGzfw.trim() === ""){
       //   this.$set(this.tableImpExcel[i],"rySjzt","错误");
       //   this.$set(this.tableImpExcel[i],"rySjjc","工资范围为空");
       //   this.tableErr.push(this.tableImpExcel[i]);
       //   continue;
       // }
       this.$set(this.tableImpExcel[i],"rySjzt","正确");
       this.$set(this.tableImpExcel[i],"rySjjc",this.tableImpExcel[i].rySjjc)   ;
       Str.push(this.tableImpExcel[i]);
     }

     return Str;
   },

   //table里是否有记录
   getExistFromTable(contrastValue){
      let lId = "";
     this.tableDBData.find( value => {
       if(contrastValue.trim() === value.ryCode.trim() ){
         lId = value.id;
       }
     })
      return lId;
   },
   //去掉空行
   getExcelNull(strErr){
     let lTemp = [];
     for(let i =0;i<strErr.length;i++){
       if(strErr[i].ryCode.toString().trim() === "" && strErr[i].ryXm.toString().trim() === ""
         && strErr[i].ryZhiwu.toString().trim() === ""&& strErr[i].ryZwjb.toString().trim() === ""){}
       else if(strErr[i].ryCode.toString().trim() === "" && strErr[i].ryXm.toString().trim() === ""){}
       else {
         lTemp.push(strErr[i]);
       }
     }
     return lTemp;
   },
   //设置id/code
   setDeptIdAndCode(value,vData,column1,column2){
     let ldeptId = 0;
     let ldeptCode = "";
     this.listTree.find(item =>{
       if(item.deptName === value){
         ldeptId = item.deptId;
         ldeptCode = item.deptCode;
       }
     })
     this.$set(vData,column1,ldeptId);
     this.$set(vData,column2,ldeptCode);
   },
   //数据处理
   setTableData(){
     let lTemp = [];
     let ltableRight = [];
     this.tableErr = [];
     this.tableAdd = [];
     this.tableEdit = [];
     this.tableDel = [];
     this.tableData = [];

     //1.校验excel
     ////console.log(this.tableImpExcel);
     ltableRight = this.getRightData();
     lTemp = this.getExcelNull(this.tableErr);
     ////console.log(ltableRight);
     // lTemp = this.tableErr;

     //2.判断excel数据状态
     let iEditId = "";
     for(let i=0;i<ltableRight.length;i++){
       iEditId = "";
       iEditId = this.getExistFromTable(ltableRight[i].ryCode)
       if (iEditId !== ""){
         this.$set(ltableRight[i],"rySjzt","修改");
         this.$set(ltableRight[i],"id",iEditId);
         this.$set(ltableRight[i],"dataState",1);
         // this.$set(ltableRight[i],"rySjjc","");


         // if(ltableRight[i].rySjdw.trim() === ""){ //跟二级单位一样
         //   this.setDeptIdAndCode(ltableRight[i].ryEjdw,ltableRight[i],"rySjdwId","rySjdwCode");
         //   this.$set(ltableRight[i],"rySjdw",ltableRight[i]["ryEjdw"]);
         // }else {
         //   this.setDeptIdAndCode(ltableRight[i].rySjdw,ltableRight[i],"rySjdwId","rySjdwCode");
         // }
         //
         // this.setDeptIdAndCode(ltableRight[i].ryEjdw,ltableRight[i],"ryEjdwId","ryEjdwCode");
         // this.setDeptIdAndCode(ltableRight[i].ryGzfw,ltableRight[i],"ryGzfwId","ryGzfwCode");
         // this.$set(ltableRight[i],"deptId",ltableRight[i]["rySjdwId"]);

         this.tableEdit.push(ltableRight[i]);
       }else {
         this.$set(ltableRight[i],"rySjzt","新增");
         this.$set(ltableRight[i],"dataState",1);
         // this.$set(ltableRight[i],"rySjjc","");


         // if(ltableRight[i].rySjdw.trim() === ""){ //跟二级单位一样
         //   this.setDeptIdAndCode(ltableRight[i].ryEjdw,ltableRight[i],"rySjdwId","rySjdwCode");
         //   this.$set(ltableRight[i],"rySjdw",ltableRight[i]["ryEjdw"]);
         // }else {
         //   this.setDeptIdAndCode(ltableRight[i].rySjdw,ltableRight[i],"rySjdwId","rySjdwCode");
         // }
         //
         // this.setDeptIdAndCode(ltableRight[i].ryEjdw,ltableRight[i],"ryEjdwId","ryEjdwCode");
         // this.setDeptIdAndCode(ltableRight[i].ryGzfw,ltableRight[i],"ryGzfwId","ryGzfwCode");
         // this.$set(ltableRight[i],"deptId",ltableRight[i]["rySjdwId"]);

         this.tableAdd.push(ltableRight[i]);
       }
     }

     lTemp = lTemp.concat(ltableRight);
    ////console.log(this.tableEdit);
    ////console.log(this.tableAdd);

     //3.判断数据库，历史遗留
     //需要做空数组判断
    this.getNoneExistFromExcel(ltableRight);
     lTemp = lTemp.concat(this.tableDel);

     this.tableData = lTemp;
   },
   // 清空
   clearDataList(){
     this.initNone();
     this.visible = false;
     this.showExist = false;
     this.fileList = [];
     //数据操作状态
     this.staOptionsAdd = '新增',//'新增不操作';
     this.staOptionsEdit = '修改',//修改不操作';
     this.staOptionsExist = '删除不操作';
     //对比数据
     this.tableData = [];
     this.tableImpExcel = [];
     this.tableDBData = [];
     //要操作数据
     this.tableErr = [];
     this.tableAdd = [];
     this.tableEdit = [];
     this.tableDel = [];
   }

  }
}
</script>

<style scoped>

</style>
